from mon_db_handler import MonDBHandler, MonDBException
from mon_config_manager import global_config

config = global_config

rw_handler = MonDBHandler.getInstance(config['db']['root_dir'])

def get_node_stats(nodeId, metricName, stat="AVERAGE", step=5, \
                   startTime=None, endTime=None):
    """In the current implemention, nodeId equals to host's name or ip
    address; stat should be one of AVERAGE, MAX and MIN
    """
    # TODO validate input args

    nodeId = str(nodeId)
    metricName = str(metricName)
    stat = str(stat)
    ret = rw_handler.read(nodeId, metricName, stat, step, \
                               startTime, endTime)
    #arr = [val[1] for val in ret[1]]
    return ret[1]

get_vm_stats = get_node_stats


def get_metric_list(nodeId):

    # TODO check the id before proceed

    ret = rw_handler.read(nodeId, 'metadata')['metric_groups']
    return ret

if __name__ == "__main__":
    import unittest

    from time import sleep, time
    from mon_center_utils import get_ip_address
    import random
    class mon_call_test(unittest.TestCase):

        local = get_ip_address('eth0')
        hosts = ['node01.hust.edu.cn']
        metrics = ['cpu_idle', 'mem_available', 'packets_out',
                   'bytes_in', 'bytes_out', 'packets_in']

        def testlast(self):
            l_ = len(self.metrics)
            for n in range(7):
                thisHost = self.hosts[random.randint(0, len(self.hosts)-1)]
                thisMetric = self.metrics[random.randint(0, l_-1)]
                arr = get_node_stats(thisHost, thisMetric)
                print thisHost, ':', thisMetric, ':', arr
                #self.assertEqual(type(arr[0]), float)
                sleep(5)

        def testrandom(self):
            l_ = len(self.metrics)
            for n in range(70):
                thisHost = self.hosts[random.randint(0, len(self.hosts)-1)]
                thisMetric = self.metrics[random.randint(0, l_-1)]
                arr = get_node_stats(thisHost, thisMetric, "AVERAGE", 5, \
                                    int(time())-60)
                print thisHost, ':', thisMetric, ':', arr
                sleep(1)

        def testcpumem(self):
            print get_cpu_mem(self.hosts[0])

        def testwrongmetric(self):
            self.assertRaises(MonDBException, get_node_stats, self.hosts[0], \
                             'load_fif', 'AVERAGE', 5)

        def testmetriclist(self):
            ret = get_metric_list(self.hosts[0])
            #print ret
            self.assertEquals(type(ret), list)

        def testvartimeinput(self):
            arr = get_node_stats(self.hosts[0], self.metrics[0], 'AVERAGE', 5, -60)
            print arr

    unittest.main()
